package com.luyuan.crm.member.service.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.OnlineMember;
import com.luyuan.crm.member.service.OnlineMemberService;
import com.ruijie.foundation.dao.support.HibernateEntityDao;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaQueryTemplate;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.security.AppUserContext;

@SuppressWarnings("unchecked")
public class OnlineMemberServiceImpl extends HibernateEntityDao<OnlineMember> implements OnlineMemberService {

    @Override
    public List<OnlineMember> getAllMember() {
        return null;
    }

    @Override
    public Page pagedQuery(CriteriaTemplate criteria, int page, int pageSize, List<Order> orders) {

        CriteriaQueryTemplate qt = new CriteriaQueryTemplate(getSessionFactory());
        return qt.pagedQuery(criteria, page, pageSize, orders);

    }

    @Override
    public Page pagedQueryOnline(CriteriaTemplate criteria, int page, int pageSize, List<Order> orders) {
        return null;
    }

    @Override
    public void onlineMember(Member member) {
        List<OnlineMember> onlineMembers = findOnlineStatus(member);
        if (!onlineMembers.isEmpty()) {
            OnlineMember onlineMember = onlineMembers.get(0);
            onlineMember.setLoginIp(AppUserContext.getRemoteAddress());
            onlineMember.setLoginTime(new Date());
            update(onlineMember);
            return;
        }

        OnlineMember onlineMember = new OnlineMember();
        onlineMember.setLoginIp(AppUserContext.getRemoteAddress());
        onlineMember.setLoginTime(new Date());
        onlineMember.setOnlineStatus(true);
        onlineMember.setMember(member);
        onlineMember.setMemberName(member.getName());
        save(onlineMember);
    }

    @Override
    public void offlineMember(Member member) {
        List<OnlineMember> onlineMembers = findOnlineStatus(member);
        if (onlineMembers.isEmpty()) {
            return;
        }

        for (OnlineMember onlineMember : onlineMembers) {
            onlineMember.setOnlineStatus(false);
            onlineMember.setLogoutTime(new Date());
            update(onlineMember);
        }
    }

    private List<OnlineMember> findOnlineStatus(Member member) {
        return createCriteria(Restrictions.eq("member", member), Restrictions.eq("onlineStatus", true)).list();
    }

    @Override
    protected void initDao() throws Exception {
        super.initDao();

        update("update OnlineMember set onlineStatus = false, logoutTime = ? where onlineStatus = true", new Date());
    }
}
